package com.bank.ui.admin;

import com.bank.dao.CustomerDAO;
import com.bank.entity.Customer;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UserManagementPanel extends JPanel {
    private JTable userTable;

    public UserManagementPanel() {
        setLayout(new BorderLayout());

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("客户编号");
        model.addColumn("客户姓名");
        model.addColumn("身份证号");
        model.addColumn("联系电话");
        model.addColumn("联系地址");

        userTable = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(userTable);
        add(scrollPane, BorderLayout.CENTER);

        // 添加操作按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("增加客户");
        JButton editButton = new JButton("修改客户");
        JButton deleteButton = new JButton("删除客户");
        JButton queryButton = new JButton("查询客户");
        JButton refreshButton = new JButton("刷新");

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 弹出增加客户界面 - 添加刷新回调
                new AddCustomerDialog(() -> refreshTable()).setVisible(true);
            }
        });

        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = userTable.getSelectedRow();
                if (selectedRow != -1) {
                    // 弹出修改客户界面 - 添加刷新回调
                    int customerID = (int) userTable.getValueAt(selectedRow, 0);
                    new EditCustomerDialog(
                            customerID,
                            () -> refreshTable()
                    ).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(UserManagementPanel.this,
                            "请选择要修改的客户！", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = userTable.getSelectedRow();
                if (selectedRow != -1) {
                    // 删除客户
                    int customerID = (int) userTable.getValueAt(selectedRow, 0);
                    int confirm = JOptionPane.showConfirmDialog(UserManagementPanel.this,
                            "确定要删除该客户吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                    if (confirm == JOptionPane.YES_OPTION) {
                        try {
                            CustomerDAO customerDAO = new CustomerDAO();
                            customerDAO.deleteCustomer(customerID);
                            // 刷新表格
                            refreshTable();
                        } catch (SQLException ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(UserManagementPanel.this,
                                    "删除客户失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(UserManagementPanel.this,
                            "请选择要删除的客户！", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 弹出查询客户界面
                new GeneralQueryDialog(new CustomerQueryHandler()).setVisible(true);
            }
        });

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(refreshButton);
        add(buttonPanel, BorderLayout.SOUTH);

        // 初始加载数据
        refreshTable();
    }

    public void refreshTable() {
        try {
            CustomerDAO customerDAO = new CustomerDAO();
            List<Customer> customers = customerDAO.getAllCustomers();

            DefaultTableModel model = (DefaultTableModel) userTable.getModel();
            model.setRowCount(0); // 清除现有数据

            for (Customer customer : customers) {
                model.addRow(new Object[]{
                        customer.getCustomerID(),
                        customer.getCustomerName(),
                        customer.getPID(),
                        customer.getTelephone(),
                        customer.getAddress()
                });
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "加载客户数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 客户查询处理器实现
    private class CustomerQueryHandler implements GeneralQueryDialog.QueryHandler {
        private final CustomerDAO dao = new CustomerDAO();

        @Override
        public String[] getQueryTypes() {
            return new String[]{"精确查询（身份证号）", "模糊查询（姓名）", "范围查询（客户编号）"};
        }

        @Override
        public List<Object> performQuery(String queryType, String queryText) throws SQLException {
            if ("精确查询（身份证号）".equals(queryType)) {
                Customer customer = dao.getCustomerByPID(queryText);
                return customer != null ? Collections.singletonList(customer) : new ArrayList<>();
            } else if ("模糊查询（姓名）".equals(queryType)) {
                return new ArrayList<>(dao.getCustomersByNameLike(queryText));
            } else if ("范围查询（客户编号）".equals(queryType)) {
                String[] range = queryText.split("-");
                int startID = Integer.parseInt(range[0]);
                int endID = Integer.parseInt(range[1]);
                return new ArrayList<>(dao.getCustomersByIDRange(startID, endID));
            }
            return new ArrayList<>();
        }

        @Override
        public String[] getColumnNames() {
            return new String[]{"客户编号", "客户姓名", "身份证号", "联系电话", "联系地址"};
        }

        @Override
        public Object[] convertToTableRow(Object result) {
            Customer customer = (Customer) result;
            return new Object[]{
                    customer.getCustomerID(),
                    customer.getCustomerName(),
                    customer.getPID(),
                    customer.getTelephone(),
                    customer.getAddress()
            };
        }
    }
}